package iCalImport;

import gui.CalView;
import gui.NewCalendarWindow;
import gui.Test;
import gui.WeekView;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.LinkedList;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;

import todo.MyTask;
import tools.OptionReader;
import calendar.CheckboxCalendar;
import calendar.ImportEvent;

/**
 * 
 * @author Michi
 * 
 */

public class SaveDialog extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 5172062122750003L;
	private JPanel contentPane;
	private JTextField auswahl;
	private File file;
	private JComboBox comboBox;
	private JCheckBox cb1;
	private JCheckBox cb2;
	private Connection connection;
	private Statement stat;
	private LinkedList<CheckboxCalendar> cals = new LinkedList<CheckboxCalendar>();
	private String[] calDropdown;
	private int idEvents = 0;
	private int speak = 0;
	private JPanel mitte;
	private SaveDialog thisinstance = this;

	// / Sprache
	// Noch nicht gesetzt!

	String[] keineAuswahl = { "keine Auswahl", "no Selection",
			"non Selectionem" };
	String[] durchsuchen = { "Durchsuchen...", "Browse...", "Scrutamini..." };
	String[] woSpeichern = {
			"In welchen Kalender soll die Datei gespeichert werden?",
			"Select the calendar you want to save the File?",
			"Ubi si file salvus fieri?" };
	String[] neuerKalender = { "Neu", "New", "Novum" };
	String[] meineK = { "Meine Kalender", "My calendar", "Mea calendarium" };
	String[] abbrechenS = { "Abbrechen", "Cancel", "Abrigavi" };
	String[] importieren = { "Importieren", "Import", "Importo" };
	String[] wasImport = { "Was soll importiert werden?",
			"What is to be imported?", "Quid importari?" };
	String[] termine = { "Termine", "Events", "Eventuum" };
	String[] aufgaben = { "Aufgaben", "Tasks", "Negotia" };
	String[] name = { "Name:", "Name:", "Nomen:" };
	String[] zuImpICS = { "Die zu importierende .ics Datei ausw\u00E4hlen:",
			"Select the .ics file to import.", "Lego .ics ad important lima." };
	String[] selectWindowName = { "iCal Datei auswählen", "Select iCal File",
			"Lego iCal File" };
	private OptionReader or;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					SaveDialog frame = new SaveDialog(null);
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */

	public SaveDialog(final Test testinstance) {

		// final Object openedfrom

		setTitle(".ics Import");

		// OptionRead Test
		or = new OptionReader();
		try {
			or.getOpionsFromFile();
		} catch (IOException e2) {

			e2.printStackTrace();
		}

		speak = Integer.parseInt(or.getLanguage());

		try {
			Class.forName("com.mysql.jdbc.Driver");
			connection = DriverManager
					.getConnection("jdbc:mysql://win9142.informatik.uni-wuerzburg.de:3306?user=awesomefireballs&password=jesus");
		} catch (ClassNotFoundException e1) {

			e1.printStackTrace();
		} catch (SQLException e1) {

			e1.printStackTrace();

		}
		// Test.iduser
		ResultSet idsCalendar;
		try {
			stat = connection.createStatement();
			stat.executeQuery("use `sopra-ws12-awesome_fireballs`;");

			idsCalendar = stat
					.executeQuery("SELECT idCalendar, name, idCreator FROM Calendar WHERE idUser = "
							+ Test.iduser + ";");

			while (idsCalendar.next()) {
				CheckboxCalendar temp = new CheckboxCalendar(
						idsCalendar.getInt("idCalendar"),
						idsCalendar.getString("name"),
						idsCalendar.getInt("idCreator"));
				cals.add(temp);
			}
		} catch (SQLException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}

		calDropdown = new String[cals.size()];
		for (int i = 0; i < cals.size(); i++) {
			calDropdown[i] = cals.get(i).getName();
		}

		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setBounds(100, 100, 382, 328);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);

		mitte = new JPanel();
		contentPane.add(mitte, BorderLayout.CENTER);
		mitte.setLayout(null);

		auswahl = new JTextField();
		auswahl.setBounds(10, 12, 194, 20);
		auswahl.setEditable(false);
		auswahl.setText(keineAuswahl[speak]);
		mitte.add(auswahl);
		auswahl.setColumns(10);

		JButton btnDurchsuchen = new JButton(durchsuchen[speak]);
		btnDurchsuchen.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				auswahl.setBackground(mitte.getBackground());

				file = FileDialog.getFiles(selectWindowName[speak]);
				if (file != null) {
					auswahl.setText(file.getName());
				}
			}
		});
		btnDurchsuchen.setBounds(214, 11, 134, 23);
		mitte.add(btnDurchsuchen);

		JLabel lblWoSollDie = new JLabel(
				"In welchen Kalender soll die Datei gespeichert werden?");
		lblWoSollDie.setBounds(10, 153, 335, 14);
		mitte.add(lblWoSollDie);

		JButton btnAbbrechen = new JButton(abbrechenS[speak]);
		btnAbbrechen.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				dispose();
			}
		});
		btnAbbrechen.setBounds(97, 237, 121, 23);
		mitte.add(btnAbbrechen);

		JButton btnImportieren = new JButton(importieren[speak]);
		btnImportieren.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (auswahl.getText().equals(keineAuswahl[speak])) {
					System.out.println("isso");
					auswahl.setBackground(Color.RED);
				} else {

					// //////////
					// Wenn Termine importieren ausgew���hlt ist.
					// //////////

					if (cb1.isSelected()) {
						ArrayList<ImportEvent> list = new ArrayList<ImportEvent>();
						list = Import.getTermine(file);
						for (ImportEvent ie : list) {
							System.out.println("\nNeues Event:");
							System.out.println("Name: " + ie.getName());
							System.out.println("Start: " + ie.getStart());
							System.out.println("Ende: " + ie.getEnd());
							System.out.println("Ort: " + ie.getOrt());
							System.out.println("Beschreibung: "
									+ ie.getDescription());
						}

						try {
							stat = connection.createStatement();
							stat.executeQuery("use `sopra-ws12-awesome_fireballs`;");

							ResultSet fete = stat
									.executeQuery("SELECT idEvents FROM `sopra-ws12-awesome_fireballs`.`Events`ORDER BY idEvents DESC LIMIT 1;");

							while (fete.next()) {
								idEvents = fete.getInt(1) + 1;
							}

							PreparedStatement ps = connection
									.prepareStatement("INSERT INTO `sopra-ws12-awesome_fireballs`.Events VALUES(?, ?, ?, ?, ?, ?, ?)");

							connection.setAutoCommit(false);

							int calID = cals.get(comboBox.getSelectedIndex())
									.getIdCalendar();

							int j = 0;
							for (ImportEvent ie : list) {

								// Dates in einen String der korrekten Form
								// bringen.
								SimpleDateFormat sdf = new SimpleDateFormat(
										"yyyy-MM-dd HH:mm:ss");

								StringBuilder sBBegin = new StringBuilder(sdf
										.format(ie.getStart()));

								StringBuilder sBEnd = new StringBuilder(sdf
										.format(ie.getEnd()));

								String beginString = sBBegin.toString();
								String endString = sBEnd.toString();

								ps.setInt(1, idEvents + j);
								ps.setInt(2, calID);
								ps.setString(3, ie.getName());
								ps.setString(4, beginString);
								ps.setString(5, endString);
								ps.setString(6, ie.getOrt());
								ps.setString(7, ie.getDescription());
								ps.addBatch();

								j++;
							}

							ps.executeBatch();
							connection.commit();

							connection.setAutoCommit(true);

						} catch (SQLException e1) {
							e1.printStackTrace();
						}

					}

					// //////////
					// Wenn Aufgaben importieren ausgew���hlt ist.
					// //////////

					if (cb2.isSelected()) {
						ArrayList<MyTask> listT = new ArrayList<MyTask>();
						listT = Import.getAufgaben(file);

						for (MyTask mt : listT) {
							System.out.println("\nNeue Aufgabe:");
							System.out.println("Name: " + mt.getName());
							System.out.println("Start: " + mt.getEnddate());
							System.out.println("Prioritaet: "
									+ mt.getPriority());
							System.out.println("Beschreibung: "
									+ mt.getDescription());
							System.out.println("Erledigt: " + mt.getDone());
						}
						try {
							stat = connection.createStatement();
							stat.executeQuery("use `sopra-ws12-awesome_fireballs`;");
							int idTask = 1;
							ResultSet fete = stat
									.executeQuery("SELECT idTask FROM `sopra-ws12-awesome_fireballs`.`Task`ORDER BY idTask DESC LIMIT 1;");

							while (fete.next()) {
								idTask = fete.getInt(1) + 1;
							}

							PreparedStatement ps = connection
									.prepareStatement("INSERT INTO `sopra-ws12-awesome_fireballs`.Task VALUES(?, ?, ?, ?, ?, ?, ?)");

							connection.setAutoCommit(false);

							int calID = cals.get(comboBox.getSelectedIndex())
									.getIdCalendar();

							int j = 0;
							for (MyTask ie : listT) {

								// Dates in einen String der korrekten Form
								// bringen.
								SimpleDateFormat sdf = new SimpleDateFormat(
										"yyyy-MM-dd HH:mm:ss");

								StringBuilder sBBegin = new StringBuilder(sdf
										.format(ie.getEnddate()));

								String beginString = sBBegin.toString();
								int done = 0;
								if(ie.getDone() == true){
									done = 1;
								}

								ps.setInt(1, idTask + j);
								ps.setInt(2, calID);
								ps.setString(3, ie.getName());
								ps.setString(4, beginString);
								ps.setInt(5, ie.getPriority());
								ps.setString(6, ie.getDescription());
								ps.setInt(7, done);
								ps.addBatch();

								j++;
							}

							ps.executeBatch();
							connection.commit();

							connection.setAutoCommit(true);
							
							testinstance.updateCalendar();

						} catch (SQLException e1) {
							e1.printStackTrace();
						}

					}
					Object kal = Test.getMainInstance().getKalender();
					if(kal instanceof CalView){
						((CalView) kal).setEs();
						((CalView) kal).setTs();
					}
					if (kal instanceof WeekView){
						((WeekView) kal).setEs();
						((WeekView) kal).setEs();
					}
					Test.getMainInstance().updateLeftPane(true);
					Test.getMainInstance().updateCalendar();
					
					dispose();

				}

			}
		});
		btnImportieren.setBounds(228, 237, 120, 23);
		mitte.add(btnImportieren);

		JLabel lblWasSollImportiert = new JLabel(wasImport[speak]);
		lblWasSollImportiert.setBounds(10, 55, 182, 14);
		mitte.add(lblWasSollImportiert);

		cb1 = new JCheckBox(termine[speak]);
		cb1.setSelected(true);
		cb1.setBounds(20, 76, 97, 23);
		mitte.add(cb1);

		cb2 = new JCheckBox(aufgaben[speak]);
		cb2.setSelected(true);
		cb2.setBounds(20, 102, 97, 23);
		mitte.add(cb2);
		comboBox = new JComboBox(calDropdown);
		comboBox.setBounds(110, 178, 166, 25);
		mitte.add(comboBox);

		JLabel lblMeineKalender = new JLabel(meineK[speak]);
		lblMeineKalender.setBounds(10, 183, 91, 14);
		mitte.add(lblMeineKalender);
		

		JButton btnNeuerKalender = new JButton(neuerKalender[speak]);
		btnNeuerKalender.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				NewCalendarWindow ncw = new NewCalendarWindow(thisinstance,
						testinstance);
				ncw.setVisible(true);
			}
		});
		btnNeuerKalender.setBounds(286, 179, 59, 24);
		mitte.add(btnNeuerKalender);

		JLabel lblDieZuImportierende = new JLabel(zuImpICS[speak]);
		contentPane.add(lblDieZuImportierende, BorderLayout.NORTH);
	}

	public void update() {
		// Test.iduser
		cals.clear();
				ResultSet idsCalendar;
				try {
					stat = connection.createStatement();
					stat.executeQuery("use `sopra-ws12-awesome_fireballs`;");

			idsCalendar = stat
					.executeQuery("SELECT idCalendar, name, idCreator FROM Calendar WHERE idUser = "
							+ Test.iduser + ";");

			while (idsCalendar.next()) {
				CheckboxCalendar temp = new CheckboxCalendar(
						idsCalendar.getInt("idCalendar"),
						idsCalendar.getString("name"),
						idsCalendar.getInt("idCreator"));
				cals.add(temp);
			}
		} catch (SQLException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}

		calDropdown = new String[cals.size()];
		for (int i = 0; i < cals.size(); i++) {
			calDropdown[i] = cals.get(i).getName();
		}
		comboBox = new JComboBox(calDropdown);
		forceRepaint();
	}
	
	public void forceRepaint() {
		paint(getGraphics());
	}
}
